﻿using NotesApp.Commands;
using NotesApp.Models;
using NotesApp.Repositories;
using System;
using System.ComponentModel;
using System.Timers;
using System.Windows;
using System.Windows.Input;

namespace NotesApp.ViewModels
{
    public class NoteViewModel : INotifyPropertyChanged
    {
        private Note _note;
        private Timer _autoSaveTimer;
        private readonly NoteRepository _noteRepository;

        public Note Note
        {
            get { return _note; }
            set
            {
                _note = value;
                OnPropertyChanged(nameof(Note));
            }
        }

        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }
        public NoteViewModel()
        {
            SaveCommand = new RelayCommand(Save);
            CancelCommand = new RelayCommand(Cancel);
            _noteRepository = new NoteRepository();

            _autoSaveTimer = new Timer(5000); // Auto-save every 5 seconds
            _autoSaveTimer.Elapsed += AutoSave;
            _autoSaveTimer.Start();
        }
        private void AutoSave(object sender, ElapsedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() => SaveImpl(false));
        }
        private void SaveImpl(bool closeWindow)
        {
            try
            {
                // Implement save logic here, e.g., assign an ID if new, update ModifiedDate
                if (Note.ID == 0)
                {
                    Note.ID = new Random().Next(1, 10000);  // Assign a new ID
                    Note.CreatedDate = DateTime.Now;
                }
                Note.ModifiedDate = DateTime.Now;

                // Save the note to the database
                _noteRepository.Update(Note);

                if (closeWindow)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show("Note saved successfully.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                        Application.Current.Windows[1]?.Close();
                    });
                }
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show($"Error saving note: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                });
            }
        }
        private void Save(object obj)
        {
            SaveImpl(true);
        }

        private void Cancel(object obj)
        {
            if (_autoSaveTimer.Enabled)
            {
                _autoSaveTimer.Stop();
            }

            Application.Current.Dispatcher.Invoke(() =>
            {
                if (MessageBox.Show("Are you sure you want to cancel? Any unsaved changes will be lost.", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Application.Current.Windows[1]?.Close();
                }
            });
        }

        private int GenerateUniqueId()
        {
            return (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }
        
        public static NoteViewModel Of(Note note)
        {
            NoteViewModel nvm = new NoteViewModel();
            nvm.Note = note;

            return nvm;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
